package com.jack.configuration;


import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.atomikos.jdbc.AtomikosDataSourceBean;

@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties
@MapperScan(basePackages= {"com.jack.mapper.user"}, sqlSessionTemplateRef = "jtaUserSqlSessionTemplate" )
public class DataSourceJTAUserConfig {

	@Bean
	@ConfigurationProperties(prefix = "spring.jta.atomikos.datasource.jta-user")
	public DataSource jtaUserDataSource() {
		return new AtomikosDataSourceBean();
	}
	
	@Bean
	public SqlSessionFactory jtaUserSqlSessionFactory(@Qualifier("jtaUserDataSource") DataSource jtaUserDataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(jtaUserDataSource);
		bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
		bean.setTypeAliasesPackage("com.jack.mapper.user");
		return bean.getObject();
	}
	
	@Bean 
	public SqlSessionTemplate jtaUserSqlSessionTemplate(@Qualifier("jtaUserSqlSessionFactory") SqlSessionFactory jtaUserSqlSessionFactory) {
		return new SqlSessionTemplate(jtaUserSqlSessionFactory);
	}
}
